
/* global alertify, Controller */

var Application = Controller.extend(Application = {
    
    controller: null,
    modules: {},
    
    init: function() {
        this.initVariables();
        this.consume_alert();
        this.consume_confirm();
        this.setupInactivityListener();
        this.setupAjaxLoader();
        this.setupUICallbacks();
    },
    
    initVariables: function() {
        this.baseURL = $("#app_base_url").val();
    },
    
    getBaseURL: function() {
        return this.baseURL;
    },
    
    /**
     * Add global AJAX configuration to show progress indication when any AJAX call
     * is triggered
     */
    setupAjaxLoader: function() {
        $(document).ready(function() {
            $("#ajaxProgressLogo").ajaxStart(function() {

                var $this = $(this);
                $this.find("#loader_static").hide('fast', function() {
                    $this.find("#loader_anim").fadeIn();
                });

            }).ajaxStop(function() {
                var $this = $(this);

                $this.find("#loader_anim").fadeOut('fast', function() {
                    $this.find("#loader_static").show();
                });
            });
        });
    },
    
    setupUICallbacks: function() {
        var self = this;
        
        $('img.member-profile-image').on('error', function() {
            self.profileImageError(this);
        });
    },
    
    profileImageError: function(img) {
        $(img).unbind('error').attr('src', App.getBaseURL() + "/img/avatar_default.jpg");
    },
    
    setupInactivityListener: function() {
        var self = this;
        var duration = $("#setting_allowed_inactivity_duration").val();

        if ( !duration ) {
            return;
        }

        var timeout = null;
        var locked = false;

        var restartTimer = function() {
            timeout = setTimeout(function() {
                if( !locked ) {
                    App.notify('lockScreen');
                }
            }, duration * 1000 * 60);
        };

        var clearTO = function() {
            if ( timeout ) {
                clearTimeout(timeout);
            }

            restartTimer();
        };

        // keep session alive
        setInterval(function() {
            if ( !locked ) {
                var keep_alive_url = $('#keep_alive_url').val();
                $.get(keep_alive_url, function(res) {
                    if( res.session_status == "inactive" ) {
                        self.notify('lockScreen');
                    }
                }, 'json');
            }
        }, 3 * 60 * 1000);

        $("html, body").mouseenter(clearTO).click(clearTO).keyup(clearTO);

        self.listen('lockScreen', function() {
            if ( !locked ) {
                $("#nav_lock_btn").click();
                locked = true;
            }
        });

        self.listen('unlockScreen', function() {
            locked = false;
        });
    },
    setController: function( controller ) {
        this.controller = controller;
    },
    
    getController: function() {
        return this.controller;
    },
    
    listen: function( event_name, callback ) {
        this.registerCallback(event_name, callback);
    },
    
    notify: function() {
        this.fireCallbacks.apply(this, arguments);
    },
    
    register: function( module_name, module ) {
        var self = this;

        if ( module ) {
            self.modules[module_name] = module;
        }
    },
    
    startModules: function() {
        for ( var module_name in this.modules ) {
            var module = this.modules[module_name];

            if ( module.hasOwnProperty('init') ) {
                module.init();
            }
        }
    },
    
    module: function(module_name) {
        if( this.modules[module_name] ) {
            return this.modules[module_name];
        }
        
        return null;
    },
     
    consume_alert: function() {
        if ( typeof _alert != 'undefined' )
            return;

        _alert = window.alert;

        alertify.set({buttonReverse: true});

        window.alert = function( message ) {
            alertify.alert(message);
        };
    },
    consume_confirm: function() {
        if ( typeof _confirm != 'undefined' )
            return;

        _confirm = window.confirm;

        window.confirm = function( message, callback ) {
            if ( callback == null ) {
                return _confirm(message);
            }

            alertify.confirm(message, function( e ) {
                if ( e && $.isFunction(callback) ) {
                    callback();
                }

                else {

                }
            });
        };
    }
});

var ui = {
    showDialog: function( options ) {
        var _default = {
            title: 'Dialog Title',
            width: '500',
            height: '500',
            content: ''
        };

        _default = $.extend(_default, options);

        $("#app_dialog").dialog(_default).html(_default['content']);
        $("#app_dialog").dialog('open');
        $("#app_dialog").parent().find(".ui-dialog-buttonpane button").addClass("btn");
    },
    hideDialog: function() {
        $("#app_dialog").dialog('close');
    },
    setAjaxContent: function( content ) {
        $("#ajax-content").html(content);
    },
    showContentPane: function( show ) {
        if ( show ) {
            $("#content-row").hide();
            $("#ajax-content").show('fast');
        }

        else {
            $("#content-row").show('fast');
            $("#ajax-content").hide();
        }
    },
    
    memberAutoComplete: function(selector, select_callback){

        $(selector).autocomplete({
            source: App.getBaseURL() + "organisation/member_autocomplete_list",
            minLength: 2,
            select: function( event, ui ) {
                if ( ui.item && $.isFunction(select_callback) ) {
                    select_callback.apply(this, [ui.item, event]);
                }
            },
            create: function() {
                $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                    return $("<li class='bg-white b-b text-sm'>")
                            .append("<span class='p-xs block'>" + item.label + "</span>").appendTo(ul);
                };

                $(this).data('ui-autocomplete')._resizeMenu = function() {
                    this.menu.element.outerWidth(275);
                };
            }
        });

    }
};

var App = new Application();
App.UI = ui;
App.register('notifications', {
    
    init: function() {
        var self = this;
        self.bindUI();
        self.updateDates();
        
        // set a timer to continually update the time ago information
        setInterval(function() {
            self.updateDates();
        }, 1000 * 60);
        
        // set a timer to continually update the time ago information
        setInterval(function() {
            self.updateNotifications();
        }, 1000 * 60 * 5);
    },
    
    bindUI: function() {
        var self = this;
        
        $("#notifications_trigger").click(function() {
            self.updateDates();
        });
        
        $(document).on('click', '.mark_read', function( e ) {
            e.preventDefault();
            e.stopPropagation();

            var read = $(this).parents('.notification-item').data('read');
            var url = $(this).attr('href');
            var params = {read: (read == 1 ? 0 : 1)};

            $.get(url, params, function( res ) {
                if ( res.status == 'success' && res.notification_type_id ) {
                    $(".notification-item").each(function() {
                        if ( $(this).data('type-id') == res.notification_type_id ) {
                          
                            var $classes = res.read == 1 ? 'read bg-white hover' : 'unread bg-light hover lter';
                            $(this).removeClass().addClass("media notification-item list-group-item " + $classes);
                            $(this).data('read', res.read);
                        }
                    });
                }

                $("#notifications_nav .count-n").html($("#notifications_nav .notification-item.unread").length);
            }, 'json');
        });

        $("#mark_all_read").click(function( e ) {
            e.preventDefault();
            e.stopPropagation();

            var url = $(this).attr('href');
            $.get(url, function( res ) {
                if ( res.status == 'success' ) {
                    $(".notification-item").data('read', 1);
                    $(".notification-item").removeClass().addClass("media notification-item list-group-item read bg-white hover");
                    $("#notifications_nav .count-n").html($("#notifications_nav .notification-item.unread").length);
                }
            }, 'json');
        });
    },
    
    updateDates: function() {
        $(".notification-item").each(function() {
            var dt = $(this).data('notification-dt');
            var m = moment(dt);
            $(this).find('.time_ago').html( m.fromNow() );
        });
    },
    
    updateNotifications: function() {
        var url = $("#latest_notifications_url").val();
        $.get(url, function(html) {
            $("#notifications_popup").html(html);
            $("#notifications_nav .count-n").html($("#notifications_nav .notification-item.unread").length);
        });
    }
});

$(document).ready(function() {
    App.init();
    App.startModules();
});

